import 'dart:async';

import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/sms_code_dao.dart';
import 'package:changxindianzishangwu/else/lib/common/index.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:changxindianzishangwu/widget/login_form_code.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'update_pwd_page2.dart';

///修改密码=》获取验证码

class UpdatePwdPage extends StatefulWidget {
  const UpdatePwdPage({Key key}) : super(key: key);

  @override
  _UpdatePwdPageState createState() => _UpdatePwdPageState();
}

class _UpdatePwdPageState extends State<UpdatePwdPage> {
  TextEditingController controller;

  @override
  void initState() {
    // TODO: implement initState
    controller = TextEditingController();

    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    EasyLoading.dismiss();
    _cancelTimer();

    super.dispose();
  }

  _getSmsCode() async {
    EasyLoading.show();
    var result = await SmsCodeDao.getCode(getUserInfo().phone,
        getUserInfo().telephone.substring(0, 2), FORGET_PASSWORD);
    EasyLoading.dismiss();
    if (result['resultCode'] !=1) {
      toast("获取验证码失败：${result["resultMsg"]}");
      return;
    }
    _startTimer();

    toast("获取验证码成功");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TopAppBar(context, "修改密码"),
      body: Container(
        color: Colors.white,
        padding: EdgeInsets.all(15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "通过已绑定手机号${TextUtil.hideNumber(getUserInfo().phone)}进行验证，请输入正确的验证码以进行下一步操作",
              style:
                  TextStyle(color: AppColor.colorDefaultText, fontSize: sp(15)),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 30),
              child: Text(
                "验证码",
                style: TextStyle(fontSize: sp(13)),
              ),
            ),
            Container(
              child: Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: TextField(
                      controller: controller,
                      keyboardType: TextInputType.number,
                      cursorColor: Colors.greenAccent,
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: "请输入验证码",
                        hintStyle: TextStyle(
                          fontSize: ScreenUtil().setSp(13),
                          color: Color.fromRGBO(153, 153, 153, 1),
                        ),
                      ),
                    ),
                  ),
                  _timeView()
                ],
              ),
            ),
            UniversalView().line(),
            Padding(
              padding: const EdgeInsets.only(top: 50),
              child: UniversalView().longBtn("下一步", () {
                if (controller.text.isEmpty) {
                  toast("请输入验证码~");
                  return;
                }
                Get.to(UpdatePwdPage2(controller.text));
              }),
            )
          ],
        ),
      ),
    );
  }

  ///---------------------倒计时 start-------------------------------------------------
  ///---------------------倒计时  end-------------------------------------------------
  String _verifyStr = '重新发送';

  TextStyle _availableStyle = TextStyle(
    fontSize: sp(12),
    color: AppColor.colorBlue,
  );


  /// 当前倒计时的秒数。
  int _seconds = 60;


  _timeView() {
    return InkWell(
      child: Text(
        '  $_verifyStr  ',
        style: _availableStyle,
      ),
      onTap: () {

        if (_seconds == 60) {
          _getSmsCode();
        }
      },
    );
  }

  Timer _timer;

  /// 启动倒计时的计时器。
  void _startTimer() {
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_seconds == 0) {

        _cancelTimer();
        _seconds = 60;
        _verifyStr="重新获取";
        if (mounted) {
          setState(() {});
        }
        return;
      }

      _seconds--;
      _verifyStr = '$_seconds' + 's重新获取';
      if (mounted) {
        setState(() {

        });
      }
    });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }
}
